package cn.com.infohold.smartcity.weex.update;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class WeexVersion {
    protected static final Pattern PATTERN = Pattern.compile("[\\s\\S]*(\\d+)\\.(\\d+)\\.(\\d+)$");

    private boolean available = true;

    private int major;
    private int minor;
    private int fixed;

    private String path;

    public String getPath() {
        return path;
    }

    public WeexVersion(String path) {
        this(path, null);
    }

    public WeexVersion(String path, String version) {
        this.path = path;
        setVersion(TextUtils.isEmpty(version) ? path : version);
    }


    public int compare(@NonNull WeexVersion version) {
        if (version == null)
            return 1;
        if (major > version.major
                || (major >= version.major && minor > version.minor)
                || (major >= version.major && minor >= version.minor && fixed > version.fixed)) {
            return 1;
        } else if (major == version.major && minor == version.minor && fixed == version.fixed) {
            return 0;
        }
        return -1;
    }

    public void setVersion(String version) {
        try {
            Matcher matcher = PATTERN.matcher(version);
            if (matcher.find()) {
                int major = Integer.parseInt(matcher.group(1));
                int minor = Integer.parseInt(matcher.group(2));
                int fixed = Integer.parseInt(matcher.group(3));
                this.major = major;
                this.minor = minor;
                this.fixed = fixed;
                return;
            }
        } catch (Exception e) {

        }
        this.major = -1;
        this.minor = -1;
        this.fixed = -1;
    }

    public String getVersion() {
        if (major >= 0 && minor >= 0 && fixed >= 0) {
            return String.format("%d.%d.%d", major, minor, fixed);
        }
        return null;
    }

    public boolean isAvailable() {
        return available;
    }

    public void setAvailable(boolean available) {
        this.available = available;
    }

    public static WeexVersion max(WeexVersion l, WeexVersion r) {
        if (l == null)
            return r;
        if (r == null)
            return l;
        int i = l.compare(r);
        if (i > 0)
            return l;
        return r;
    }
}